package jsvmcore

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

type (
	// javascript调试
	Debugger struct {
		vm *JsVM
	}
)

func NewDebugger(vm *JsVM) *Debugger {
	return &Debugger{
		vm: vm,
	}
}

func (d *Debugger) CheckBreakpoint(line int) bool {
	if d.vm.Debug {
		fmt.Printf("⏸️断点命中 at line %d\n", line)
		d.showDebugPrompt()
	}
	return true
}

func (d *Debugger) showDebugPrompt() {
	scanner := bufio.NewScanner(os.Stdin)
	fmt.Println("调试命令: c(继续),v(查看变量【全局变量】), q(退出)")
	for {
		fmt.Print("(debug) ")
		if !scanner.Scan() {
			break
		}
		cmd := strings.TrimSpace(scanner.Text())
		if strings.HasPrefix(cmd, "c") || strings.HasPrefix(cmd, "continue") {
			fmt.Println("继续执行...")
			return
		} else if strings.HasPrefix(cmd, "q") || strings.HasPrefix(cmd, "quit") {
			fmt.Println("退出")
			d.vm.ForceDestory()
			return
		} else if strings.HasPrefix(cmd, "v ") || strings.HasPrefix(cmd, "view ") {
			varName := strings.Split(cmd, " ")[1]
			value := d.vm.State.Get(varName)
			fmt.Printf("%s:%v\n", varName, value)
		} else {
			fmt.Println("未知命令")
		}
	}
}
